package com.dougmccune.charts.gantt
{
	import flash.events.Event;
	
	import mx.controls.DataGrid;
	import mx.controls.dataGridClasses.DataGridColumn;
	import mx.core.IFactory;
	import mx.events.DataGridEvent;
	import mx.events.ListEvent;
	import mx.core.ClassFactory;
	import mx.collections.ArrayCollection;

	public class GanttDataGrid extends DataGrid
	{
		[Bindable]
		private var _ganttItemEditor:IFactory;
			
		[Bindable]
		public var max:Number = 0;
			
		[Bindable]
		public var taskHeaderWidth:Number = 60;
		
		public function set ganttItemEditor(value:IFactory):void {
			_ganttItemEditor = value;
			
			(this.columns[1] as DataGridColumn).itemRenderer = _ganttItemEditor;
			
		}
		
		public function get ganttItemEditor():IFactory {
			return _ganttItemEditor;
		}
		
		override protected function createChildren():void {
			super.createChildren();
		
			_ganttItemEditor = new ClassFactory(GanttItemEditor);
			
			var taskColumn:DataGridColumn = new DataGridColumn();
			taskColumn.dataField = "title";
			taskColumn.headerText = "Task";
			taskColumn.width = taskHeaderWidth;
			
			var mainColumn:DataGridColumn = new DataGridColumn();
			mainColumn.itemRenderer = ganttItemEditor;
			mainColumn.rendererIsEditor = true;
			
			
			this.columns = [taskColumn, mainColumn];
			
			this.addEventListener(Event.CHANGE, changeListener);
		}
		
		private function changeListener(event:ListEvent):void {
			var grid:DataGrid = event.currentTarget as DataGrid;
            
            var dp:ArrayCollection = grid.dataProvider as ArrayCollection;
            	
            	
            	
            for(var i:int=0; i<dp.length; i++) {
            	var item:Object = dp.getItemAt(i);
            	item.selected = (i == grid.selectedIndex);
            	dp.setItemAt(item, i);
            }
		}
	}
}